import uuid

from app.models import BaseModel
from app.models.userModel import User
from tools import db

tb_chapter_courseware = db.Table(
    "api_chapter_courseware",
    db.Column(
        "chapter_id",
        db.String(32),
        db.ForeignKey("api_chapter.id", ondelete="CASCADE", onupdate="CASCADE"),
    ),
    db.Column(
        "courseware_id",
        db.Integer,
        db.ForeignKey("api_courseware.id", ondelete="CASCADE", onupdate="CASCADE"),
    ),
    db.Column("env_status", db.Enum("0", "1", "2"), default="0"),
    db.Column("env_start_time", db.Integer, default=None),
    db.Column("env_end_time", db.Integer, default=None),
)


def gen_id():
    return uuid.uuid1().hex

# 课程
class Course(db.Model, BaseModel):
    __tablename__ = "api_course"
    id = db.Column(db.String(32), default=gen_id, primary_key=True)
    name = db.Column(db.String(120), unique=True, index=True)
    describe = db.Column(db.TEXT)
    isSystem = db.Column(db.Boolean, index=True, default=0)
    cover_path = db.Column(db.String(120), default=None)
    status = db.Column(db.Enum("0", "1", "2"), default="0")

    user_id = db.Column(db.Integer, db.ForeignKey(User.id))
    chapter_set = db.relationship(
        "Chapter", backref="course", lazy="dynamic", cascade="all, delete-orphan"
    )

    def to_status_dict(self):
        def add_status(infos):
            try:
                for chapter in infos:
                    chapter_uuid = chapter["uuid"]
                    for courseware in chapter["child"]:
                        courseware_id = courseware["courseware_id"]
                        third_info = db.session.execute(
                            f"""select * from api_chapter_courseware
                            where courseware_id={courseware_id} and chapter_id='{chapter_uuid}'
                            """
                        ).fetchone()
                        courseware.update(
                            {
                                "env_status": third_info[2],
                                "env_start_time": third_info[3],
                                "env_stop_time": third_info[4],
                            }
                        )
                return infos
            except Exception as e:  # noqa
                return infos

        chapter_coursewares_infos = add_status(
            [_.to_dict() for _ in self.chapter_set.order_by(Chapter.sort_num.asc()).all()]
        )
        resp_dict = {
            "course_uuid": self.id,
            "course_name": self.name,
            "describe": self.describe,
            "cover_path": self.cover_path if self.cover_path else None,
            "chapter_coursewares": chapter_coursewares_infos,
            "users": [_.to_dict() for _ in self.relate_user],
            "status": self.status,
        }
        return resp_dict

    def course_users(self):
        return [_.to_dict() for _ in self.relate_user]

    def to_dict(self):
        return {
            "course_uuid": self.id,
            "course_name": self.name,
            "describe": self.describe,
            "cover_path": self.cover_path if self.cover_path else None,
            "chapter_coursewares": [
                _.to_dict()
                for _ in self.chapter_set.order_by(Chapter.sort_num.asc()).all()
            ],
            "users": [_.to_dict() for _ in self.relate_user],
            "status": self.status,
        }

# 章节
class Chapter(db.Model, BaseModel):
    __tablename__ = "api_chapter"
    id = db.Column(db.String(32), default=gen_id, primary_key=True)
    name = db.Column(db.String(120), index=True)
    # 当前章节相关课程
    course_id = db.Column(db.String(32), db.ForeignKey(Course.id))
    sort_num = db.Column(db.Integer, default=0)
    # 当前章节的课件
    coursewares = db.relationship(
        "Courseware",
        secondary=tb_chapter_courseware,
        backref=db.backref("api_chapter", lazy=True),
        lazy="dynamic",
    )

    def to_dict(self):
        return {
            "uuid": self.id,
            "name": self.name,
            "sort_num": self.sort_num,
            "child": [_.to_dict() for _ in self.coursewares.all()],
        }
